from PyQt5.QtWidgets import (QWidget, QTableWidget, QTableWidgetItem, QVBoxLayout, QHBoxLayout, 
                             QPushButton, QLabel, QLineEdit, QTextEdit, QMessageBox, QHeaderView,
                             QDialog, QFormLayout, QDialogButtonBox)
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QFont, QColor, QIcon

from service.DataDictionaryService import DataDictionaryService
from config.log_config import AntLogger

class AddEditDictionaryDialog(QDialog):
    """添加/编辑数据字典对话框"""
    def __init__(self, parent=None, entry=None):
        super().__init__(parent)
        self.entry = entry
        self.is_edit_mode = entry is not None
        self._init_ui()
    
    def _init_ui(self):
        """初始化界面"""
        self.setWindowTitle('编辑字典项' if self.is_edit_mode else '添加字典项')
        self.setMinimumWidth(400)
        
        # 创建表单布局
        layout = QFormLayout(self)
        
        # 键输入框
        self.key_edit = QLineEdit()
        if self.is_edit_mode:
            self.key_edit.setText(self.entry.dict_key)
            self.key_edit.setReadOnly(True)  # 编辑模式下键不可修改
        layout.addRow('键名:', self.key_edit)
        
        # 值输入框
        self.value_edit = QLineEdit()
        if self.is_edit_mode:
            self.value_edit.setText(self.entry.dict_value)
        layout.addRow('值:', self.value_edit)
        
        # 描述输入框
        self.desc_edit = QTextEdit()
        self.desc_edit.setMaximumHeight(100)
        if self.is_edit_mode and self.entry.dict_desc:
            self.desc_edit.setText(self.entry.dict_desc)
        layout.addRow('描述:', self.desc_edit)
        
        # 按钮
        self.button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        self.button_box.accepted.connect(self.accept)
        self.button_box.rejected.connect(self.reject)
        layout.addRow(self.button_box)
        
        # 设置样式
        self.setStyleSheet("""
            QDialog {
                background-color: #f0f8ff;
            }
            QLineEdit, QTextEdit {
                border: 1px solid #87ceeb;
                border-radius: 3px;
                padding: 4px;
                background-color: white;
            }
            QPushButton {
                background-color: #87ceeb;
                color: white;
                border: none;
                border-radius: 3px;
                padding: 6px 12px;
            }
            QPushButton:hover {
                background-color: #5cacee;
            }
        """)
    
    def get_data(self):
        """获取对话框数据"""
        return {
            'dict_key': self.key_edit.text().strip(),
            'dict_value': self.value_edit.text().strip(),
            'dict_desc': self.desc_edit.toPlainText().strip()
        }

class DataDictionaryView(QWidget):
    """数据字典视图类"""
    def __init__(self):
        super().__init__()
        self.service = DataDictionaryService()
        self._init_ui()
        self._load_data()
    
    def _init_ui(self):
        """初始化界面"""
        self.setWindowTitle('数据字典管理')
        self.resize(800, 600)
        
        # 主布局
        main_layout = QVBoxLayout()
        
        # 标题
        title_label = QLabel('数据字典管理')
        title_label.setAlignment(Qt.AlignCenter)
        title_font = QFont('微软雅黑', 14, QFont.Bold)
        title_label.setFont(title_font)
        main_layout.addWidget(title_label)
        
        # 按钮区域
        button_layout = QHBoxLayout()
        
        self.add_btn = QPushButton('添加')
        self.add_btn.clicked.connect(self._add_entry)
        
        self.edit_btn = QPushButton('编辑')
        self.edit_btn.clicked.connect(self._edit_entry)
        
        self.delete_btn = QPushButton('删除')
        self.delete_btn.clicked.connect(self._delete_entry)
        
        self.refresh_btn = QPushButton('刷新')
        self.refresh_btn.clicked.connect(self._load_data)
        
        button_layout.addWidget(self.add_btn)
        button_layout.addWidget(self.edit_btn)
        button_layout.addWidget(self.delete_btn)
        button_layout.addStretch()
        button_layout.addWidget(self.refresh_btn)
        
        main_layout.addLayout(button_layout)
        
        # 表格控件
        self.table = QTableWidget()
        self.table.setColumnCount(6)
        self.table.setHorizontalHeaderLabels(['ID', '键名', '值', '描述', '创建时间', '更新时间'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.table.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)  # 禁止编辑
        self.table.setSelectionBehavior(QTableWidget.SelectRows)  # 选择整行
        self.table.setSelectionMode(QTableWidget.SingleSelection)  # 单选
        self.table.setAlternatingRowColors(True)  # 交替行颜色
        
        main_layout.addWidget(self.table)
        
        self.setLayout(main_layout)
        
        # 设置样式
        self.setStyleSheet("""
            QWidget { 
                background-color: #f0f8ff; 
                font-family: '微软雅黑';
            }
            QTableWidget { 
                background-color: white;
                border: 1px solid #87ceeb;
                font: 12px '微软雅黑';
                alternate-background-color: #e6f7ff;
            }
            QHeaderView::section { 
                background-color: #87ceeb;
                color: white;
                padding: 4px;
                font-weight: bold;
                border: none;
            }
            QPushButton { 
                background-color: #87ceeb;
                color: white;
                border: none;
                border-radius: 3px;
                padding: 6px 12px;
                min-width: 80px;
            }
            QPushButton:hover { 
                background-color: #5cacee;
            }
            QLabel { 
                color: #333333;
                margin: 5px 0;
            }
        """)
    
    def _load_data(self):
        """加载数据到表格"""
        try:
            AntLogger.info('开始加载数据字典数据')
            entries = self.service.getAllDictionaryEntries()
            
            self.table.setRowCount(len(entries))
            for row, entry in enumerate(entries):
                # ID
                id_item = QTableWidgetItem(str(entry.id))
                id_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, 0, id_item)
                
                # 键名
                key_item = QTableWidgetItem(entry.dict_key)
                self.table.setItem(row, 1, key_item)
                
                # 值
                value_item = QTableWidgetItem(entry.dict_value)
                self.table.setItem(row, 2, value_item)
                
                # 描述
                desc_item = QTableWidgetItem(entry.dict_desc if entry.dict_desc else '')
                self.table.setItem(row, 3, desc_item)
                
                # 创建时间
                create_time_item = QTableWidgetItem(str(entry.create_time))
                create_time_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, 4, create_time_item)
                
                # 更新时间
                update_time_item = QTableWidgetItem(str(entry.update_time))
                update_time_item.setTextAlignment(Qt.AlignCenter)
                self.table.setItem(row, 5, update_time_item)
            
            AntLogger.info(f'数据字典数据加载完成，共{len(entries)}条')
        except Exception as e:
            AntLogger.error(f'加载数据字典数据异常: {str(e)}')
            QMessageBox.critical(self, '错误', f'加载数据失败: {str(e)}')
    
    def _add_entry(self):
        """添加字典项"""
        dialog = AddEditDictionaryDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            data = dialog.get_data()
            if not data['dict_key'] or not data['dict_value']:
                QMessageBox.warning(self, '警告', '键名和值不能为空')
                return
            
            success, message = self.service.createDictionaryEntry(
                data['dict_key'], data['dict_value'], data['dict_desc']
            )
            
            if success:
                QMessageBox.information(self, '成功', '添加成功')
                self._load_data()  # 刷新数据
            else:
                QMessageBox.warning(self, '失败', f'添加失败: {message}')
    
    def _edit_entry(self):
        """编辑字典项"""
        selected_rows = self.table.selectedItems()
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要编辑的项')
            return
        
        # 获取选中行的键
        row = selected_rows[0].row()
        dict_key = self.table.item(row, 1).text()
        
        # 获取完整数据
        entry = self.service.getDictionaryByKey(dict_key)
        if not entry:
            QMessageBox.warning(self, '警告', f'未找到键为{dict_key}的数据')
            return
        
        # 打开编辑对话框
        dialog = AddEditDictionaryDialog(self, entry)
        if dialog.exec_() == QDialog.Accepted:
            data = dialog.get_data()
            if not data['dict_value']:
                QMessageBox.warning(self, '警告', '值不能为空')
                return
            
            success, message = self.service.updateDictionaryEntry(
                data['dict_key'], data['dict_value'], data['dict_desc']
            )
            
            if success:
                QMessageBox.information(self, '成功', '更新成功')
                self._load_data()  # 刷新数据
            else:
                QMessageBox.warning(self, '失败', f'更新失败: {message}')
    
    def _delete_entry(self):
        """删除字典项"""
        selected_rows = self.table.selectedItems()
        if not selected_rows:
            QMessageBox.warning(self, '警告', '请先选择要删除的项')
            return
        
        # 获取选中行的键
        row = selected_rows[0].row()
        dict_key = self.table.item(row, 1).text()
        
        # 确认删除
        reply = QMessageBox.question(self, '确认删除', 
                                    f'确定要删除键为「{dict_key}」的数据吗？',
                                    QMessageBox.Yes | QMessageBox.No, 
                                    QMessageBox.No)
        
        if reply == QMessageBox.Yes:
            success, message = self.service.deleteDictionaryEntry(dict_key)
            
            if success:
                QMessageBox.information(self, '成功', '删除成功')
                self._load_data()  # 刷新数据
            else:
                QMessageBox.warning(self, '失败', f'删除失败: {message}')